import logging
import time
import json
import re
from django.utils import timezone
from django.http import JsonResponse
from django.core.cache import cache
from django.contrib.auth.models import AnonymousUser
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db import models

logger = logging.getLogger('api_requests')


class APIRequestLoggingMiddleware:
    """API请求日志中间件"""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 记录请求开始时间
        start_time = time.time()

        # 记录请求信息
        if request.path.startswith('/api/'):
            logger.info(f"API请求开始: {request.method} {request.path}")

        response = self.get_response(request)

        # 记录响应信息
        if request.path.startswith('/api/'):
            duration = time.time() - start_time
            logger.info(f"API请求完成: {request.method} {request.path} - {response.status_code} - {duration:.3f}s")

        return response
 